<template>
  <div>
    <h3>身份信息</h3>
    <div class="table-body">
      <vxe-toolbar>
        <template #buttons>
          <el-row :gutter="10">
            <el-col :span="4" style="display: flex;">
              <el-button v-if="false" type="success" icon="el-icon-plus" size="medium" @click="insertEvent">新增记录
              </el-button>
              <el-button type="success" icon="el-icon-printer" size="medium" @click="exportData">导出</el-button>
              <el-button type="success" icon="el-icon-printer" size="medium" @click="printEvent">打印</el-button>
            </el-col>
            <el-col :span="4">
              <el-button-group style="display: flex;">
                <el-select v-model="searchForm.empTypeId" style="margin-left: 20px;" size="small" multiple collapse-tags
                  filterable clearable placeholder="选择工作类型">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in dict_emp_type" :key="index">
                  </el-option>
                </el-select>
                <el-button type="success" size="small" @click="searchForm.empTypeId = Object.keys(dict_emp_type)">全选
                </el-button>
              </el-button-group>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.sportId" style="margin-left: 20px;" size="small" collapse-tags filterable
                clearable placeholder="选择运动项目">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.genderId" style="margin-left: 20px;" size="small" collapse-tags filterable
                clearable placeholder="选择性别">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_gender" :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
                style="margin: 0 10px;">搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="4">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row
        highlight-current-row :loading="loading" :data="dataList" @sort-change="sortChange">
        <vxe-table-column field="name" title="教职员" sortable></vxe-table-column>
        <vxe-table-column field="sport" title="运动项目" sortable></vxe-table-column>
        <vxe-table-column field="empType" title="专职" sortable></vxe-table-column>
        <vxe-table-column field="empType2" title="兼职" sortable></vxe-table-column>
        <vxe-table-column field="gender" title="性别" sortable></vxe-table-column>
        <vxe-table-column field="nation" title="民族" sortable></vxe-table-column>
        <vxe-table-column field="birthday" title="生日" sortable></vxe-table-column>
        <vxe-table-column field="address" title="地址" sortable></vxe-table-column>
        <vxe-table-column field="idNo" title="身份证号码" sortable></vxe-table-column>
        <vxe-table-column field="issuing" title="签发机关" sortable></vxe-table-column>
        <vxe-table-column field="validDateBegin" title="有效期开始" sortable></vxe-table-column>
        <vxe-table-column field="validDateEnd" title="有效期结束" sortable></vxe-table-column>
        <vxe-table-column field="" title="操作" width="60">
          <template #default="{ row,rowIndex }">
            <el-button @click="editEvent(row,rowIndex)" type="success" size="medium" icon="el-icon-edit" circle></el-button>
            <el-button v-if="false" @click="deleteEvent(row)" type="danger" size="medium" icon="el-icon-delete" circle>
            </el-button>
          </template>
        </vxe-table-column>
        <vxe-table-column field="createUser" title="录入人" sortable></vxe-table-column>
        <vxe-table-column field="checkUser" title="审核人" sortable>
          <template #default="{ row }">
            <span v-if="row.checkUserId">{{row.checkUser}}</span>
            <el-link v-else @click="checkedEvent(row)" type="success">{{row.checkUser}}</el-link>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize"
        :total="page.totalResult" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
        @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <vxe-modal v-model="insertModal" title="身份信息">
      <template #default>
        <el-form inline-message ref="insertForm" :rules="rules" :model="insertForm" label-width="110px">
          <el-form-item label="教职员" prop="name">
            <el-input v-model="insertForm.name"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="genderId">
            <el-select v-model="insertForm.genderId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_gender" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="民族" prop="nation">
            <el-input v-model="insertForm.nation"></el-input>
          </el-form-item>
          <el-form-item label="生日" prop="birthday">
            <el-date-picker type="date" placeholder="选择日期" v-model="insertForm.birthday" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="insertForm.address"></el-input>
          </el-form-item>
          <el-form-item label="身份证号码" prop="idNo">
            <el-input v-model="insertForm.idNo"></el-input>
          </el-form-item>
          <el-form-item label="签发机关" prop="issuing">
            <el-input v-model="insertForm.issuing"></el-input>
          </el-form-item>
          <el-form-item label="有效期开始" prop="validDateBegin">
            <el-date-picker type="date" placeholder="选择日期" v-model="insertForm.validDateBegin" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="有效期结束" prop="validDateEnd">
            <el-date-picker type="date" placeholder="选择日期" v-model="insertForm.validDateEnd" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" size="small" @click="insertModal = false">取消</el-button>
            <el-button type="success" size="small" icon="el-icon-s-promotion" @click="insertSave">保存</el-button>
          </el-form-item>
        </el-form>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
  import {
    empByOrg,
    getPersonByOrgEmp,
    empByOrg_update,
    empByOrg_check,
    empByOrg_select
  } from '@/api/person.js'
  import {
    sport_by_org,
    pId2sportIds4emp1,
    genEmpType,
    employee_type,
    userId2EmpName
  } from '@/api/dict.js'
  export default {
    data() {
      return {
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        insertModal: false,
        dict_sport: {},
        dict_pid_emp: {},
        dict_pid_birthday: {},
        dict_pid_gender: {},
        dict_pid_sport: {},
        dict_pid_empTypeId: {},
        dict_pid_jempTypeId: {},
        dict_emp_type: {},
        dict_userId2empName: {},
        dict_gender: {
          1: '男',
          2: '女'
        },
        dict_pid_idNo: {},
        insertForm: {
          name: '',
          genderId: '',
          nation: '',
          birthday: '',
          address: '',
          idNo: '',
          issuing: '',
          validDateBegin: '',
          validDateEnd: '',
        },
        searchForm: {
          empTypeId: '',
          genderId: '',
          sportId: '',
        },
        sportItemData: [],
        rules: {
          name: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          birthday: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          idNo: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
        },
        isInsert: true,
        flowId: '',
        pid: '',
        search: false,
        currentIndex: null,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.empByOrg()
      })
    },
    computed: {
      openDateValid() {
        if (this.insertForm.validDateBegin && this.insertForm.validDateEnd) {
          if (this.insertForm.validDateBegin > this.insertForm.validDateEnd) {
            this.$message.error('开始时间必须小于结束时间！')
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      }
    },
    watch: {
      filterName(val) {
    	if(!val){
    	  this.page = {
    	  currentPage: 1,
    	  pageSize: 10,
    	  totalResult: 0,
    	  }
    	  this.search = false
    	  this.findList()
    	}
      }
    },
    methods: {
      sortChange() {
        this.page.currentPage = 1
        this.page.pageSize = this.defaultDataList.length
        this.findList()
      },
      clearTableFilter() {
        this.searchForm = {
          empTypeId: '',
          genderId: '',
          sportId: '',
        }
        this.empByOrg()
      },
      searchSubmit() {
        let data = {}
        if (this.searchForm.empTypeId) data.empTypeIdStr = this.searchForm.empTypeId.join(',')
        if (this.searchForm.genderId) data.gender = this.searchForm.genderId
        if (this.searchForm.sportId) data.sportId = this.searchForm.sportId
        empByOrg_select(data).then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.page = {
              currentPage: 1,
              pageSize: 10,
              totalResult: 0
            }
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          empByOrg_delete({
            flowId: row.flowId
          }).then(res => {
            if (res.code === 200) {
              this.defaultDataList.forEach((item,index)=>{
              	if(item.flowId == row.flowId){
              	  this.defaultDataList.splice(index,1)
              	}
              })
              this.init_data(this.defaultDataList)
              this.findList()
              this.$message.success('删除成功！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      checkedEvent(row) {
        this.$confirm('注意：审核过之后，该条数据将不能再被修改', '审核', {
          confirmButtonText: '√通过审核',
          cancelButtonText: '放弃审核',
          type: 'warning'
        }).then(() => {
          empByOrg_check({
            pId: row.pid
          }).then(res => {
            if (res.code === 200) {
              this.empByOrg()
              this.$message.success('已审核.！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消审核.'
          });
        });
      },
      editEvent(row,rowIndex) {
        this.currentIndex = rowIndex
        if (row.checkUserId) {
          this.$message.warning('已经审核过的数据不能修改')
        } else {
          this.flowId = row.flowId
          this.pid = row.pid
          this.insertForm.name = row.name
          this.insertForm.genderId = row.genderId
          this.insertForm.nation = row.nation
          this.insertForm.birthday = row.birthday
          this.insertForm.address = row.address
          this.insertForm.idNo = row.idNo
          this.insertForm.issuing = row.issuing
          this.insertForm.validDateBegin = row.validDateBegin
          this.insertForm.validDateEnd = row.validDateEnd
          this.isInsert = false
          this.insertModal = true
        }
      },
      insertSave() {
        this.$refs.insertForm.validate((valid) => {
          if (valid && this.openDateValid) {
            let data = {}
            if(this.insertForm.genderId)data.gender = this.insertForm.genderId
            if(this.insertForm.birthday)data.birthday = this.$moment(this.insertForm.birthday).format(
              'YYYY-MM-DD') + ' 00:00:00'
            if(this.insertForm.validDateBegin) data.validDateBegin = this.$moment(this.insertForm.validDateBegin)
              .format('YYYY-MM-DD') + ' 00:00:00'
            if(this.insertForm.validDateEnd) data.validDateEnd = this.$moment(this.insertForm.validDateEnd).format(
              'YYYY-MM-DD') + ' 00:00:00'
            if(this.insertForm.nation)data.nation = this.insertForm.nation
            if(this.insertForm.address)data.address = this.insertForm.address
            if(this.insertForm.issuing)data.issuing = this.insertForm.issuing
            if(this.insertForm.name)data.name = this.insertForm.name
            if(this.insertForm.idNo)data.idCardNumber = this.insertForm.idNo
            data.pId = this.pid
            if (this.isInsert) {
              empByOrg_insert(data).then(res => {
                if (res.code === 200) {
                  this.dataList.unshift(res.data)
                  this.defaultDataList.push(res.data)
                  this.init_data(this.defaultDataList)
                  this.page.totalResult+=1
                  this.$refs.XTable.setCurrentRow(this.dataList[0])
                  this.$message.success('保存成功')
                  this.insertSuccess = true
                  this.insertModal = false
                } else {
                  this.$message.error('保存失败')
                }
              })
            } else {
              empByOrg_update(data).then(res => {
                if (res.code === 200) {
                  this.dict_pid_emp[res.data.pid] = res.data.name
                  this.dict_pid_birthday[res.data.pid] = res.data.birthday
                  this.dict_pid_gender[res.data.pid] = this.dict_gender[res.data.gender]
                  this.dict_pid_idNo[res.data.pid] = res.data.idCardNumber
                  this.init_data(this.defaultDataList)
                  this.$message.success('修改成功')
                  this.insertModal = false
                } else {
                  this.$message.warning('修改失败，请检查数据是否合法')
                }
              })
            }
          } else {
            return false;
          }
        })
      },
      insertEvent() {
        this.insertForm = {
          name: '',
          genderId: '',
          nation: '',
          birthday: '',
          address: '',
          idNo: '',
          issuing: '',
          validDateBegin: '',
          validDateEnd: '',
        }
        this.isInsert = true
        this.insertModal = true
      },
      sportChange() {
        this.insertForm.sportItemId = ''
        sport_item_by_sportId({
          sportId: this.insertForm.sportId
        }).then(res => {
          if (res.code === 200) {
            this.sportItemData = res.data
          }
        })
      },
      exportData() {
        this.$refs.XTable.exportData({
          filename: this.$store.state.user.org + '教职员' + this.$route.meta.title,
          type: 'csv',
          data: this.search?this.dataList:this.defaultDataList
        })
      },
      printEvent() {
        let topHtml = '<h2>身份信息</h2>'
        this.searchEvent()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '身份信息',
            beforePrintMethod: ({
              content
            }) => {
              return topHtml + content
            }
          })
        }, 1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      empByOrg() {
        empByOrg().then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item => {
          item.name = this.dict_pid_emp[item.pid]
          item.birthday = this.$moment(this.dict_pid_birthday[item.pid]).format('YYYY-MM-DD') == 'Invalid date' ?
            '' : this.$moment(this.dict_pid_birthday[item.pid]).format('YYYY-MM-DD')
          item.gender = this.dict_pid_gender[item.pid]
          if (this.dict_pid_gender[item.pid] == '男') {
            item.genderId = '1'
          } else {
            item.genderId = '2'
          }
          item.idNo = this.dict_pid_idNo[item.pid]
          item.sport = this.dict_pid_sport[item.pid]
          item.empType = this.dict_pid_empTypeId[item.pid]
          item.empType2 = this.dict_pid_jempTypeId[item.pid]
          item.validDateBegin = this.$moment(item.validDateBegin).format('YYYY-MM-DD') == 'Invalid date' ? '' : this
            .$moment(item.validDateBegin).format('YYYY-MM-DD')
          item.validDateEnd = this.$moment(item.validDateEnd).format('YYYY-MM-DD') == 'Invalid date' ? '' : this
            .$moment(item.validDateEnd).format('YYYY-MM-DD')
          item.createUser = this.dict_userId2empName[item.createUserId]
          if (item.checkUserId) {
            item.checkUser = this.dict_userId2empName[item.checkUserId]
          } else {
            item.checkUser = '未审核'
          }
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          genEmpType(true).then(res => {
            let dict_pid_empTypeId = {}
            let dict_pid_jempTypeId = {}
            res.data.forEach(item => {
              dict_pid_empTypeId[item.pid] = item.empTypeId
              dict_pid_jempTypeId[item.pid] = item.height
            })
            this.dict_pid_empTypeId = dict_pid_empTypeId
            this.dict_pid_jempTypeId = dict_pid_jempTypeId
          }).then(() => {
            employee_type().then(res2 => {
              this.dict_emp_type = res2
              for (let key in this.dict_pid_empTypeId) {
                this.dict_pid_empTypeId[key] = this.dict_emp_type[this.dict_pid_empTypeId[key]]
              }
              for (let key in this.dict_pid_jempTypeId) {
                let arr = this.dict_pid_jempTypeId[key].split(',')
                let arr2 = []
                arr.forEach(item => {
                  arr2.push(this.dict_emp_type[item])
                })
                this.dict_pid_jempTypeId[key] = arr2.join(',')
              }
            })
          })
          userId2EmpName().then(res => {
            this.dict_userId2empName = res
          })
          getPersonByOrgEmp().then(res => {
            let dict_pid_emp = {}
            let dict_pid_birthday = {}
            let dict_pid_gender = {}
            let dict_pid_idNo = {}
            res.data.forEach(item => {
              dict_pid_emp[item.pid] = item.name
              dict_pid_birthday[item.pid] = item.birthday
              dict_pid_gender[item.pid] = this.dict_gender[item.genderId]
              dict_pid_idNo[item.pid] = item.idNo
            })
            this.dict_pid_emp = dict_pid_emp
            this.dict_pid_birthday = dict_pid_birthday
            this.dict_pid_gender = dict_pid_gender
            this.dict_pid_idNo = dict_pid_idNo
          }).then(() => {
            pId2sportIds4emp1().then(res => {
              this.dict_pid_sport = res
            }).then(() => {
              sport_by_org().then(res2 => {
                this.dict_sport = res2
                for (let key in this.dict_pid_sport) {
                  let arr = this.dict_pid_sport[key].split(',')
                  let sportArr = []
                  arr.forEach(item => {
                    sportArr.push(this.dict_sport[item])
                  })
                  this.dict_pid_sport[key] = sportArr.join(',')
                }
                resolve()
              })
            })
          })
        })
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult/this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length-1])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>
